<?php

namespace App\Console\Commands;

use App\Curl;
use App\OperationRecord;
//use App\RunGameConfig;
use App\RunGameRank;
use App\RunGameReward;
use App\RunGameSeason;
use App\RunGamePrize as Price;
use Illuminate\Console\Command;
use DB;

class RunGamePrice extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'rungame:price';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '赛季结束发放赛季奖励';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // 检测脚本是否重复执行
        $this->check();
        $time = time();

        DB::beginTransaction();

        //找到未发放奖励的赛季
        $season_ids = RunGameSeason::where('end_at', '<=', $time)->where('is_price', RunGameSeason::PRICE_NO)->pluck('id')->toArray();
        if (count($season_ids)) {
            foreach ($season_ids as $season_id) {
                //找到该赛季的参赛用户数据
                $gamgLogs = RunGameRank::select('user_id', 'integral')->where('season_id', $season_id)->orderByDesc('integral')->orderBy('updated_at')->get()->toArray();
                //奖励
                $rewards = RunGameReward::where('is_use', RunGameReward::USE_YES)->where('id', '!=', 0)->orderBy('ranking')->pluck('id')->toArray();
                $price_insert = [];
                $operation_insert = [];
                $push_insert = [];
                $users = [];
//                $integral_pre = RunGameConfig::value('integral_pre');
                if (count($gamgLogs)) {
                    foreach ($gamgLogs as $key => $gamgLog) {
                        $users[] = $gamgLog['user_id'];
                        $season_title = RunGameSeason::where('id', $season_id)->value('title');
                        if (!Curl::PushNum($gamgLog['user_id'])) {
                            DB::rollBack();

                            return ['status' => 2, 'message' => '发送系统消息失败'];
                        }
                        //前三名发放特殊奖励
                        if ($key === 0) {
                            //第一名
                            $price_insert[] = [
                                'user_id' => $gamgLog['user_id'],
                                'season_id' => $season_id,
                                'reward_id' => $rewards[0],
                                'status' => Price::STATUS_WAITTING,
                                'number' => 1,
                                'created_at' => $time,
                                'updated_at' => $time,
                            ];
                            //消息
                            $push_insert[] = [
                                'title' => '系统消息',
                                'content' => "您在健康大闯关游戏{$season_title}赛季获得了一等奖，请及时到游戏界面领取",
                                'ctime' => date('Y-m-d H:i:s',$time),
                                'user_id' => $gamgLog['user_id']
                            ];
                        } else if ($key === 1) {
                            //第二名
                            $price_insert[] = [
                                'user_id' => $gamgLog['user_id'],
                                'season_id' => $season_id,
                                'reward_id' => $rewards[1],
                                'status' => Price::STATUS_WAITTING,
                                'number' => 1,
                                'created_at' => $time,
                                'updated_at' => $time,
                            ];
                            //消息
                            $push_insert[] = [
                                'title' => '系统消息',
                                'content' => "您在健康大闯关游戏{$season_title}赛季获得了二等奖，请及时到游戏界面领取",
                                'ctime' => date('Y-m-d H:i:s',$time),
                                'user_id' => $gamgLog['user_id']
                            ];
                        } else if ($key === 2) {
                            //第三名
                            $price_insert[] = [
                                'user_id' => $gamgLog['user_id'],
                                'season_id' => $season_id,
                                'reward_id' => $rewards[2],
                                'status' => Price::STATUS_WAITTING,
                                'number' => 1,
                                'created_at' => $time,
                                'updated_at' => $time,
                            ];
                            //消息
                            $push_insert[] = [
                                'title' => '系统消息',
                                'content' => "您在健康大闯关游戏{$season_title}赛季获得了三等奖，请及时到游戏界面领取",
                                'ctime' => date('Y-m-d H:i:s',$time),
                                'user_id' => $gamgLog['user_id']
                            ];
                        }
//                        else {
//                            if ($gamgLog['integral']) {
//
//                                //剩余的发放金币
//                                $price_insert[] = [
//                                    'user_id' => $gamgLog['user_id'],
//                                    'season_id' => $season_id,
//                                    'reward_id' => 0,
//                                    'status' => Price::STATUS_RECEIVED,
//                                    'number' => $gamgLog['integral'] * $integral_pre,
//                                    'created_at' => $time,
//                                    'updated_at' => $time,
//                                ];
//                                //收益记录
//                                $operation_insert[] = [
//                                    'type' => OperationRecord::TYPE_GAME,
//                                    'number' => '+'.$gamgLog['integral'] * $integral_pre.'金币',
//                                    'name' => OperationRecord::$TypyDisplay[OperationRecord::TYPE_GAME],
//                                    'status' => OperationRecord::STATUS_YES,
//                                    'user_id' => $gamgLog['user_id'],
//                                    'create_time' => date('Y-m-d H:i:s', $time),
//                                    'reflect_type' => 1,
//                                    'reflect_name' => '跑步游戏',
//                                    'transaction_time' => date('Y-m-d H:i:s', $time),
//                                ];
//                                //消息
//                                $push_insert[] = [
//                                    'title' => '系统消息',
//                                    'content' => "您在健康大闯关游戏{$season_title}赛季获得了参与奖，答对题数的金币已经到账",
//                                    'ctime' => date('Y-m-d H:i:s',$time),
//                                    'user_id' => $gamgLog['user_id']
//                                ];
//                                //增加金币
//                                if (!DB::table('t_member')->where('c_id', $gamgLog['user_id'])->increment('coin_number', $gamgLog['integral'] * $integral_pre)) {
//                                    DB::rollBack();
//
//                                    logger('金币发放失败');
//                                    exit('金币发放失败');
//                                }
//                            }
//                        }
                    }
                }
                //添加记录
                if (count($price_insert)) {
                    if (!Price::insert($price_insert)) {
                        DB::rollBack();

                        logger('奖励记录添加失败');
                        exit('奖励记录添加失败');
                    }
                }
                //添加收益记录
                if (count($operation_insert)) {
                    if (!OperationRecord::insert($operation_insert)) {
                        DB::rollBack();

                        logger('收益记录添加失败');
                        exit('收益记录添加失败');
                    }
                }
                //发送消息
                if (count($push_insert)) {
                    if (!DB::table('jpush')->insert($push_insert)) {
                        DB::rollBack();

                        logger('发送消息失败');
                        exit('发送消息失败');
                    }

                    //jpush
                    foreach ($push_insert as $item) {
                        Curl::PushOne($item['user_id'], $item['content']);
                    }
                }
            }
        }
        //修改赛季奖励发放状态
        if (!RunGameSeason::whereIn('id', $season_ids)->update(['is_price' => RunGameSeason::PRICE_YES])) {
            DB::rollBack();

            logger('修改赛季奖励发放状态失败');
            exit('修改赛季奖励发放状态失败');
        }

        DB::commit();

        exit('OK');

    }

    public function check()
    {
        $file = 'rungame_price.lock';
        $lock_file = storage_path($file);
        if (!flock($this->fp = fopen($lock_file, 'w'), LOCK_NB | LOCK_EX)) {
            //无法取得锁就退出
            logger($this->description . ' 脚本尝试重复启动');
            die('cannot get lock，already running?');
        }
        register_shutdown_function('unlink', $lock_file);
    }
}
